package com.example;

import com.example.a01.Component1;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Locale;
import java.util.Map;

@SpringBootApplication
public class Spring01Application {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException {
        ConfigurableApplicationContext context = SpringApplication.run(Spring01Application.class, args);
		/*
			1. BeanFactory介绍
			- ApplicationContext的父接口
			- Spring的核心容器
		 */
        System.out.println(context);

        /*
        	2. BeanFactory作用
        	- 控制反转、基本的依赖注入、直至bean的生命周期的各种功能，都由其实现类提供
         */
        Field singletonObjects = DefaultSingletonBeanRegistry.class.getDeclaredField("singletonObjects");
        singletonObjects.setAccessible(true);
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        Map<String, Object> map = (Map<String, Object>) singletonObjects.get(beanFactory);
//		map.forEach((k, v) -> System.out.println(k + "-->" + v));
        map.entrySet().stream().filter(e -> e.getKey().startsWith("component"))
                .forEach((e) -> System.out.println(e.getKey() + "-->" + e.getValue()));

		/*
			3. ApplicationContext功能
		 */
        // MessageSource父接口
        System.out.println(context.getMessage("hi", null, Locale.CHINA));
        System.out.println(context.getMessage("hi", null, Locale.ENGLISH));

        // ResourcePatternResolver父接口
        Resource[] resources = context.getResources("classpath*:META-INF/spring.factories");
        for (Resource resource : resources) {
            System.out.println(resource);
        }

        // EnvironmentCapable父接口
        System.out.println(context.getEnvironment().getProperty("JAVA_HOME"));
        System.out.println(context.getEnvironment().getProperty("MAVEN_HOME"));
        System.out.println(context.getEnvironment().getProperty("server.port"));

        // ApplicationEventPublisher父接口
//        context.publishEvent(new UserRegisterEvent(context));
        context.getBean(Component1.class).register();

    }

}
